package com.softserveinc.moviedbapp.application;

import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.preference.PreferenceManager;
import android.util.Log;

import com.softserveinc.moviedbapp.broadcastreceiver.ConnectivityReceiver;
import com.softserveinc.moviedbapp.broadcastreceiver.SDCardMountedReceiver;
import com.softserveinc.moviedbapp.manager.DataManager;

public class MovieDBApplication extends Application {

	private DataManager dataProvider;
	private Settings mSettings;
	private ConnectivityReceiver mConnectivityReceiver;
	private BroadcastReceiver mSDCardMountedReceiver;

	private static final String TAG = MovieDBApplication.class.getSimpleName();

	@Override
	public void onCreate() {
		super.onCreate();
		Log.d(TAG, "MOVIEDB Application STARTED");

		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

		mSettings = Settings.getInstance();
		mSettings.setmPreferences(prefs);

		dataProvider = new DataManager(getApplicationContext(), mSettings);

		/* open database */
		Log.d(TAG, "OPENING THE DATABASE");
		dataProvider.openDatabase();

		/* register broadcast receiver for connection */
		mConnectivityReceiver = new ConnectivityReceiver(dataProvider);
		registerReceiver(mConnectivityReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

		/* register broadcast receiver for sd card checking */
		mSDCardMountedReceiver = new SDCardMountedReceiver(dataProvider);
		IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
		filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
		filter.addDataScheme("file");
		registerReceiver(mSDCardMountedReceiver, filter);
	}

	public DataManager getDataProvider() {
		return dataProvider;
	}

	@Override
	public void onTerminate() {
		super.onTerminate();

		/* close database */
		Log.d(TAG, "CLOSING THE DATABASE");
		dataProvider.closeDatabase();
	}



}
